<?php
namespace app\api\controller\yexam;

use app\admin\model\SourceConfig;
use app\admin\model\yexam\ComboCategory;
use app\admin\model\yexam\ComboList;
use app\admin\model\yexam\Fav;
use app\admin\model\yexam\Note;
use app\admin\model\yexam\QuestionLog;
use app\admin\model\yexam\UserCombo;
use app\common\controller\Api;
use app\common\model\TimeUser;

/**
 * 科目
 * @ApiSector  (科目)
 * @ApiRoute   (/api/yexam/subject)
 */
class Subject extends Api
{
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['index','unit','kemu','huli','getuser_login'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];
    /**
     * @ApiInternal
     * 获取科目列表
     */
    public function kemu()
    {
        $page = $this->request->post('page');
        $limit = $this->request->post('limit');
        $subject = new \addons\yexam\service\Subject();
        $data = $subject->getSubjectListKemu($page,$limit);
        $this->success('请求成功', $data);
    }
    /**
     * @ApiTitle (获取科目列表)
     * @ApiRoute (/api/yexam/subject/huli)
     * @ApiMethod (POST)
     * @ApiParams (name=page,type=integer,required=false,desciption=页码)
     * @ApiParams (name=limit,type=integer,required=false,description=每页显示的数量)
     * @ApiParams (name=tagId,type=integer,required=true,description=终端设备id)
     * @ApiReturnParams  (name=msg,type=string,required=true,sample=请求成功)
     * @ApiReturnParams (name=data,type=object,required=true,sample={'id':'1','short_name':'医学'}
     * @ApiReturnParams ({'code':'1','msg' : "请求成功"})
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function huli()
    {
        $page = $this->request->post('page');
        $limit = $this->request->post('limit');
        $tagId = $this->request->post('tagId'); //====== 终端id
        $config = SourceConfig::get($tagId);
        $subject = new \addons\yexam\service\Subject();
        if (is_null($config))
            $this->error('请求异常,请联系管理员');
        //==== 全科目
        if ($config['subject'] == 0) {
            $categoryId = '';//需要调用的科目id
            $isCategory = 2;
        }
        //===== 科目id
        elseif ($config['subject'] == 1) {
            $categoryId = $config['subject_ids'];//需要调用的科目id
            $isCategory = 1;
        }
        //======== 按科目顶级进行展示
        elseif($config['subject'] == 3) {
            $categoryId = $config['subject_cat_top_ids'];
            $isCategory = 3;
        }
        //=== 科目分类，混合分类
        else {   //   subject == 2
            $category = new \app\common\model\Category();
            $subject = new \app\admin\model\yexam\Subject();
            $categoryList = $category->where('id','in',$config['subject_cat_ids'])->select();
            foreach ($categoryList as $key => $value){//  二级
                $categoryList[$key]['category_bname'] = $value['bname'];
                $three = $category->where('pid',$value['id'])->select();//第三级
                if (count($three) != 0){
                    foreach ($three as $th => $thValue){
                        $three[$th]['subjects'] = $subject->where('category_id',$thValue['id'])->select();
                    }
                    $categoryList[$key]['subjects'] = $three;
                    $categoryList[$key]['is_end'] = 0;
                }else{
                    $categoryList[$key]['subjects'] = $subject->where('category_id',$value['id'])->select();
                    $categoryList[$key]['is_end'] = 1;
                }
            }
            $isCategory = 0;
            $this->success('请求成功',['total'=> count($categoryList),'data'=>$categoryList,'type' => 4]);
        }
        $data = $subject->getSubjectFenkemu($page,$limit,$categoryId,$isCategory);
        $this->success('请求成功', $data);
    }
    /**
     * 控制登录
     * @ApiInternal
     */
    public function getuser_login()
    {
        $this->success('请求成功', [5]);
    }
    /**
     * @ApiTitle (获取科目列表|搜索科目)
     * @ApiSummary (可通过科目全称，英文名称，简称)，以及科目分类进行科目的分页以及数量的限制
     * @ApiMethod (GET)
     * @ApiParams (name=page,type=integer,required=false,description=页码，默认为第一页)
     * @ApiParams (name=limit,type=integer,required=false,description=每页显示数据数量，每页显示100)
     * @ApiParams (name=category_id,type=integer,required=true,description=分类id，必填)
     * @ApiParams (name=search,type=string,required=false,description=科目关键字)
     * @ApiReturnParams (name=msg,type=string,required=true,sample=请求成功)
     * @ApiReturn ({msg: "请求成功",data: "[]"})
     */
    public function index()
    {
        $page = $this->request->param('page') ?? 1;
        $limit = $this->request->param('limit') ?? 100;
        $categoryId = $this->request->param('category_id');
        $tagId = $this->request->param('tagId'); //====== 终端id
        $config = SourceConfig::get($tagId);
        if (!is_null($config))
        {
            $categoryId = $config['subject_cat_top_ids'];
            $where['category_id'] = ['in',$categoryId];
        }
        $search = $this->request->param('search');
        if (!empty($search)) {
            $subject = new \app\admin\model\yexam\Subject();
            $where['subject_name'] = ['like',"%{$search}%"];
            $data['data'] = $subject
                ->where($where)
                ->whereOr('en_name', 'like', "%{$search}%")
                ->whereOr('short_name', 'like', "%{$search}%")
                ->whereOr("subject_code","LIKE","%$search%")
                ->page("1, 100")
                ->order('weigh asc')
                ->select();
            $data['total'] = count($data['data']);
        } else {
            $subject = new \addons\yexam\service\Subject();
            $data = $subject->getSubjectList($page,$limit,$categoryId);
        }
        ///=================== 班次
        $package = new \app\admin\model\Package;
        // content_json to content
        if ($data['data']) {
            foreach ($data['data'] as &$item) {
                $item['package_content'] = [];
                if ($item['package_ids']) {
                    $package_ids = explode(',', $item['package_ids']);
                    $item['package_content'] = collection($package->where('id', 'in', $package_ids)->select())->toArray();
                }
                if ($item['content_json']) {
                    $item['content'] = json_decode($item['content_json']);
                } else {
                    $item['content'] = null;
                }
                unset($item['content_json']);
            }
            unset($item);
        }
        $this->success('请求成功', $data);
    }
    /**
     * @ApiTitle (获取科目下的章节，分级返回)
     * @ApiParams (name=subject_id,type=integer,required=true,description=科目id)
     * @ApiParams (name=type,type=integer,required=true,description=是否需要显示试题数量)
     * @ApiParams (name=unit_id,type=integer,required=true,description=默认为0，章节id)
     * @ApiParams (name=page,type=integer,required=true,description=页码)
     * @ApiParams (name=limit,type=integer,required=true,description=数量限制)
     * @ApiHeaders (name=token,type=string,required=true,description=token)
     * @ApiMethod (POST)
     * @ApiReturnParams (name=msg,type=string,required=true,smaple=请求成功)
     * @ApiReturnParams (name=data,type=object,rquired=true,smaple="{}")
     * @ApiReturn ('{"code": "0","data": "[]","msg": "请求成功"}')
     */
    public function unit(){
        $subject_id = $this->request->post('subject_id');
        if ($this->request->has('type'))
        {
            $unit = new \app\admin\model\yexam\Unit();
            $data = $unit->where('subject_id',$subject_id)->field('id,unit_name as name,pid,is_last')->where('status',1)->select();
            $note = new Note();
            $favorite = new Fav();
            $log = new QuestionLog();
            foreach($data as &$v){
                $unit = new \addons\yexam\service\Unit();
                $v['scale'] = $this->auth->id>0?$unit->right_scale($v['id'],$this->auth->id):0;     //正确率
                $v['total_num'] = $unit->getUnitQuestionNum($v['id']);          //章节题目总数
                $v['test_num'] = $this->auth->id>0?$unit->getUnitQuestionTestNum($v['id'],$this->auth->id):0;       //章节题目已答题
                $v['error_num'] = $log->where('unit_id',$v['id'])->where('state',2)->count();//错题数量
                $v['favorite_num'] = $favorite->where('unit_id',$v['id'])->count();
                $v['note_num'] = $note->where('unit_id',$v['id'])->count();
            }
            $this->success('请求成功',['data' => $data]);
        }
        $unit_id = $this->request->post('unit_id',0);
        $page = $this->request->post('page');
        $limit = $this->request->post('limit');
        $subject = new \addons\yexam\service\Subject();
        $isFree = $subject->getFreeUnit($subject_id);
        if (!$isFree)
        {
            $data['data'] = [];
        }else{
            $data = $subject->getUnitList($subject_id,$unit_id,$page,$limit);
            $note = new Note();
            $favorite = new Fav();
            $log = new QuestionLog();
            foreach($data['data'] as &$v){
                $unit = new \addons\yexam\service\Unit();
                $v['scale'] = $this->auth->id>0?$unit->right_scale($v['id'],$this->auth->id):0;     //正确率
                $v['total_num'] = $unit->getUnitQuestionNum($v['id']);          //章节题目总数
                $v['test_num'] = $this->auth->id>0?$unit->getUnitQuestionTestNum($v['id'],$this->auth->id):0;       //章节题目已答题
                $v['error_num'] = $log->where('unit_id',$v['id'])->where('state',2)->count();//错题数量
                $v['favorite_num'] = $favorite->where('unit_id',$v['id'])->count();
                $v['note_num'] = $note->where('unit_id',$v['id'])->count();
            }
        }
        $data['is_free'] = $isFree;
        $user = new \app\common\model\User();
        $class_title = (\app\admin\model\yexam\Subject::get($subject_id))->short_name;
        $user->where('id',$this->auth->id)->setField('class_title',$class_title);
        $this->success('请求成功', $data);
    }
    /**
     * @ApiInternal
     *获取指定科目下的练习情况
     */
    public function question_info(){
        $subject_id = $this->request->post('subject_id');
        $subject = new \addons\yexam\service\Subject();
        $total = $subject->getSubjectQuestionNum($subject_id);  //总数
        $test_num = $subject->getSubjectQuestionTestNum($subject_id,$this->auth->id);   //练习数量
        $right_num = $subject->getSubjectQuestionRightNum($subject_id,$this->auth->id); //正确数量

        $this->success('请求成功',['total'=>$total,'test_num'=>$test_num,'right_num'=>$right_num,'scale'=>empty($right_num)?0:(intval($right_num/$test_num,2)*100)]);
    }
    /**
     * @ApiTitle (已经购买的科目列表)
     * @ApiHeaders (name=token,type=string,required=true,description=token)
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function buySubjectAll()
    {
        $subjectId = $this->request->param('subject_id');
        $userCombo = new UserCombo();
        $lists = $userCombo->where('user_id',$this->auth->id)->select();
        foreach ($lists as $key => $value)
        {
            $subject = new \app\admin\model\yexam\Subject();
            $subject = $subject->where('id',$value['subject_id'])->find();
            $subjectName = $subject->short_name;
            $combo = new ComboList();
            $comboName = $combo->where('id',$value['pay_comboid'])->value('combo_name');
            if(strtotime($value['invalid_time']) < time())
                $comboName = "试用版";
            $lists[$key]['name'] = $subjectName."-".$comboName;
            $lists[$key]['time'] = date("Y-m-d",strtotime($value['invalid_time']));
            $lists[$key]['short_name'] = $subjectName;
            $lists[$key]['subject'] = $subject;
        }
        $data['data'] = $lists;
        $favorite = new Fav();
        $data['favorite']  = $favorite->where('user_id',$this->auth->id)->where('subject_id',$subjectId)->count();
        $questionLog = new QuestionLog();
        $data['error_num'] = $questionLog->where('user_id',$this->auth->id)->where('subject_id',$subjectId)->where('state',0)->count();
        $note = new Note();
        $data['note_num'] = $note->where('user_id',$this->auth->id)->where('subject_id',$subjectId)->count();
        $this->success('',$data);
    }
    /**
     * @ApiTitle (获取科目对应的题型)
     * @ApiParams (name=subject_id,type=integer,required=true,description=科目id)
     * @ApiReturnParams (name=msg,type=string,required=true,sample=请求成功)
     * @ApiReturnParams (name=data,type=object,required=true,smaple="{}")
     * @ApiReturn ({msg:"请求成功",data:"{}"})
     */
    public function getQuestionType()
    {
        $subjectId = $this->request->param('subject_id');
        $subject = new \app\admin\model\yexam\Subject();
        $question_category_id = $subject->where('id',$subjectId)->value('question_category_id');
        $category = new ComboCategory();
        $extend = $category->where('category_id',$question_category_id)->value('extend');
        $list = json_decode($extend);
        $this->success('请求成功',$list);
    }
    /**
     * @ApiTitle (设置考试时间)
     * @ApiMethod (POST)
     * @ApiParams (name=subject_id,type=integer,required=true,description=科目id)
     * @ApiParams (name=time,type=string,required=true,description=考试时间)
     * @ApiParams (name=type,type=string,required=true,description=请求方式。默认set，用于设置考试时间)
     */
    public function setSubjectTime(){
        $subjectId = $this->request->param('subject_id');
        $time = $this->request->param('time');
        $type= $this->request->param('type','set');
        $timeUser = new TimeUser();
        $result = $timeUser->where('subject_id',$subjectId)->find();
        if ($type === 'get')
            $this->success('请求成功',$result);
        if (is_null($result))
        {
            $timeUser->insert([
                'user_id' => $this->auth->id,
                'subject_id' => $subjectId,
                'time' => strtotime($time)
            ]);
            $this->success('设置成功');
        }else
        {
            $result->time = strtotime($time);
            $result->save();
            $this->success('修改成功');
        }
    }
    /**
     * @ApiTitle (获取科目信息)
     * @ApiMethod (All)
     */
    public function getSubjectInfo(){
        $subjectId = $this->request->param("id");
        $subject = \app\admin\model\yexam\Subject::get($subjectId);
        $this->success("请求成功",$subject);
    }
}
